<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.name" class="filter-item w-200" size="medium" placeholder="菜品名称"></el-input>
            <el-select v-model="query.supply_type" multiple class="filter-item" style="width: 250px" size="medium" placeholder="请选择供应类型">
                <el-option
                        v-for="item in supplyTypeData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                </el-option>
            </el-select>
            <el-select v-model="query.food_type" clearable class="filter-item w-200" size="medium" placeholder="请选择菜品种类">
                <el-option
                        v-for="item in foodTypeData"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                    <span style="float: left">{{ item.name }}</span>
                    <span v-if="item.status === 0" style="float: right; color: #8492a6; font-size: 13px; font-style: italic">已停用</span>
                </el-option>
            </el-select>
            <el-button class="filter-item"   size="medium" icon="el-icon-search" @click="fetchList(true)">搜 索</el-button>
            <el-button class="filter-item" type="primary" size="medium" icon="el-icon-plus" style="float: right" v-permission="'foods.store'" @click="addFood">新 增</el-button>
        </div>
        <el-table :data="foodData" v-loading="loading" border style="width: 100%">
            <el-table-column width="50px" label="#" align="center">
                <template slot-scope="scope" >
                    {{query.size * (query.page-1) + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" align="center"></el-table-column>
            <el-table-column prop="description" label="描述" align="center"></el-table-column>
            <el-table-column label="供应类型" align="center">
                <template slot-scope="scope">
                    <span v-if="scope.row.supply_type === 1">早餐</span>
                    <span v-if="scope.row.supply_type === 2">中餐</span>
                    <span v-if="scope.row.supply_type === 3">晚餐</span>
                    <span v-if="scope.row.supply_type === 12">早中餐</span>
                    <span v-if="scope.row.supply_type === 13">早晚餐</span>
                    <span v-if="scope.row.supply_type === 23">中晚餐</span>
                    <span v-if="scope.row.supply_type === 123">早中晚餐</span>
                </template>
            </el-table-column>
            <el-table-column label="菜品种类" align="center">
                <template slot-scope="scope">
                    <div v-for="item in foodTypeData" :key="item.id">
                        <span v-if="item.id === scope.row.food_type_id">{{ item.name }}</span>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="状态" align="center">
                <template slot-scope="scope">
                    <i class="el-icon-check" v-if="scope.row.status === 1" />
                    <i class="el-icon-close" v-else />
                </template>
            </el-table-column>
            <!--<el-table-column-->
                    <!--prop="thumb_image"-->
                    <!--header-align="center"-->
                    <!--align="center"-->
                    <!--width="150px"-->
                    <!--label="菜品样图">-->
                <!--<template slot-scope="scope">-->
                    <!--<el-popover-->
                            <!--placement="right"-->
                            <!--title=""-->
                            <!--trigger="hover">-->
                        <!--<img :src="scope.row.full_thumb_images" width="200px" height="200px" />-->
                        <!--<img slot="reference" v-bind:src="scope.row.full_thumb_images" :alt="scope.row.full_thumb_images" style="max-height: 50px;max-width: 130px">-->
                    <!--</el-popover>-->
                <!--</template>-->
            <!--</el-table-column>-->
            <el-table-column prop="updated_at" label="更新时间" align="center" width="300px"></el-table-column>
            <el-table-column label="操作" align="center" width="200px">
                <template slot-scope="scope">
                    <el-button class="filter-item" icon="el-icon-edit" type="primary" size="mini" v-permission="'foods.update'" @click="editFood(scope.row)">编 辑</el-button>
                    <!--<el-button class="filter-item" type="danger" size="mini" @click="delFood(scope.row.id)">删除</el-button>-->
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
        <el-dialog :title="foodFormTitle" width="700px" :visible.sync="dialogVisible">
            <el-form :model="foodForm" :rules="rules" ref="foodForm" label-width="100px" class="demo-foodForm">
                <el-form-item label="名称" prop="name">
                    <el-input style="width: 90%" v-model="foodForm.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="description">
                    <el-input style="width: 90%" type="textarea" v-model="foodForm.description"></el-input>
                </el-form-item>
                <el-form-item label="供应类型" prop="supply_type">
                    <el-select style="width: 90%" v-model="foodForm.supply_type" multiple placeholder="请选择">
                        <el-option
                                v-for="item in supplyTypeData"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="菜品种类" prop="food_type_id">
                    <el-select style="width: 90%" v-model="foodForm.food_type_id" placeholder="请选择">
                        <el-option
                                v-for="item in foodTypeData"
                                :key="item.id"
                                v-if="item.status === 1"
                                :label="item.name"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="状态" prop="status">
                    <el-switch
                            v-model="foodForm.status"
                            active-color="#13ce66"
                            inactive-color="#ff4949"
                            :active-value="1"
                            :inactive-value="0">
                    </el-switch>
                </el-form-item>
                <!--<el-form-item label="菜品样图" prop="image">-->
                    <!--<el-upload-->
                            <!--class="avatar-uploader"-->
                            <!--:show-file-list="false"-->
                            <!--:action="uploadUrl()"-->
                            <!--:on-success="handleAvatarSuccess"-->
                            <!--:data="uploadData"-->
                            <!--:headers="myheaders"-->
                            <!--:before-upload="beforeAvatarUpload">-->
                        <!--<img v-if="full_thumb_images" :src="full_thumb_images" class="avatar-thumb">-->
                        <!--<i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
                    <!--</el-upload>-->
                    <!--<span class="form-item-notice">图片大小320px*320px</span>-->
                <!--</el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible=false">取消</el-button>
                <el-button type="primary" @click="submitFoodForm" :loading="btnLoading">保存</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import { fetchFoods, addFood, editFood, delFood } from '@/api/food'
    import { fetchFoodTypes } from '@/api/data'
    import { getToken } from '@/utils/auth'
    export default {
      name: 'list',
      data() {
        return {
          loading: true,
          total: 0,
          query: {
            food_type: '',
            supply_type: [],
            name: '',
            size: 10,
            page: 1
          },
          queryFoodType: {
            status: 1
          },
          foodData: [],
          myheaders: {
            Accept: 'application/json',
            Authorization: 'Bearer ' + getToken()
          },
          uploadData: {
            width: 300,
            height: 320
          },
          foodForm: {
            id: '',
            name: '',
            description: '',
            supply_type: [],
            image: '',
            thumb_image: '',
            status: 1,
            food_type_id: ''
          },
          foodFormTitle: '',
          dialogVisible: false,
          btnLoading: false,
          supplyTypeData: [
            {
              value: 1,
              label: '早餐'
            },
            {
              value: 2,
              label: '中餐'
            },
            {
              value: 3,
              label: '晚餐'
            }
          ],
          foodTypeData: [],
          foodTypeDataDisabled: [],
          full_thumb_images: '',
          option: '',
          rules: {
            name: [
              { required: true, message: '请输入菜品名称', trigger: ['blur', 'change'] },
              { min: 2, max: 20, message: '输入的菜品名称长度在2 ~ 20个字符之间' }
            ],
            supply_type: [
              { required: true, message: '请选择供应类型', trigger: ['blur', 'change'] }
            ],
            food_type_id: [
              { required: true, message: '请选择菜品种类', trigger: ['blur', 'change'] }
            ]
          }
        }
      },
      methods: {
        // 删除菜品
        delFood(id) {
          this.$confirm('确定删除该菜品?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            delFood(id).then(res => {
              this.$message.success('删除成功')
              this.fetchList()
            }).catch(err => {
              this.$handleNotFound(err, '菜品不存在')
            })
          })
        },
        // 编辑菜品
        editFood(row) {
          if (this.$refs['foodForm'] !== undefined) {
            this.$refs['foodForm'].clearValidate()
          }
          this.option = 'edit'
          this.foodFormTitle = '编辑菜品'
          this.dialogVisible = true
          Object.existAssign(this.foodForm, row)
          if (row.supply_type === 123) {
            this.foodForm.supply_type = [1, 2, 3]
          } else if (row.supply_type === 12) {
            this.foodForm.supply_type = [1, 2]
          } else if (row.supply_type === 13) {
            this.foodForm.supply_type = [1, 3]
          } else if (row.supply_type === 23) {
            this.foodForm.supply_type = [2, 3]
          } else if (row.supply_type === 1) {
            this.foodForm.supply_type = [1]
          } else if (row.supply_type === 2) {
            this.foodForm.supply_type = [2]
          } else if (row.supply_type === 3) {
            this.foodForm.supply_type = [3]
          }
          this.full_thumb_images = row.full_thumb_images
          // 判断菜品所属菜品种类是否被禁用，若是则把当前菜品种类赋空，重新选择
          if (this.foodTypeDataDisabled.indexOf(this.foodForm.food_type_id) >= 0) {
            this.foodForm.food_type_id = ''
          }
        },
        // 新增菜品
        addFood() {
          this.resetForm('foodForm')
          this.option = 'add'
          this.foodFormTitle = '新增菜品'
          this.dialogVisible = true
          this.full_thumb_images = ''
          Object.assign(this.foodForm, this.$options.data().foodForm)
        },
        // 提交菜品表单
        submitFoodForm() {
          this.btnLoading = true
          this.$refs['foodForm'].validate((valid) => {
            if (valid) {
              // 通过校验
              if (this.option === 'add') {
                addFood(this.foodForm).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('添加成功')
                    this.fetchList()
                    this.dialogVisible = false
                  }
                  this.btnLoading = false
                }).catch(err => {
                  this.$handleNotFound(err)
                  this.btnLoading = false
                })
              }
              if (this.option === 'edit') {
                editFood(this.foodForm, this.foodForm.id).then(res => {
                  if (res.result === 'failed') {
                    this.$message.error(res.msg)
                  } else {
                    this.$message.success('编辑成功')
                    this.fetchList()
                    this.dialogVisible = false
                  }
                  this.btnLoading = false
                }).catch(() => {
                  this.btnLoading = false
                })
              }
            } else {
              this.btnLoading = false
            }
          })
        },
        fetchList(resetPage = false) {
          this.loading = true
          if (resetPage === true) {
            this.query.page = 1
          }
          // 获取当前学校下的菜品列表
          fetchFoods(this.query).then(res => {
            this.foodData = res.data
            this.loading = false
            this.total = res.meta.total
          })
        },
        // 重置表单验证
        resetForm(formName) {
          // 第一次新增数据时为空对象undefined
          if (this.$refs[formName] !== undefined) {
            this.$refs[formName].resetFields()
          }
        },
        uploadUrl() {
          const url = process.env.BASE_API + '/uploads?dir=images'
          return url
        },
        beforeAvatarUpload(file) {
          const isJPG = file.type.indexOf('image') > -1
          const isLt2M = file.size / 1024 / 1024 < 10
          if (!isJPG) {
            this.$message.error('上传图片格式错误!')
          }
          if (!isLt2M) {
            this.$message.error('上传图片大小不能超过 10MB!')
          }
          return isJPG && isLt2M
        },
        handleAvatarSuccess(res, file) {
          this.full_thumb_images = URL.createObjectURL(file.raw)
          this.foodForm.thumb_image = res.thumb
          this.foodForm.image = res.photo
        },
        handleSizeChange(size) {
          this.query.size = size
          this.fetchList()
        },
        handleCurrentChange(page) {
          this.query.page = page
          this.fetchList()
        }
      },
      created() {
        this.fetchList()
        // 获取当前学校下的菜品种类列表
        fetchFoodTypes().then(res => {
          this.foodTypeData = res.foodTypes
          // 取出被禁用的菜品种类id
          for (let i = 0; i < res.foodTypes.length; i++) {
            if (res.foodTypes[i].status === 0) {
              this.foodTypeDataDisabled.push(res.foodTypes[i].id)
            }
          }
        })
      }
    }
</script>

<style scoped>
    .avatar-uploader {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
        width: 178px;
        height: 178px;
    }
    .avatar-uploader:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar-thumb {
        width: 178px;
        height: 178px;
    }
    .el-icon-check{
        color: green;
    }
    .el-icon-close{
        color: red;
    }
</style>
